package org.example.test_03.Service.Impl;

import org.example.test_03.Domian.ReturnData;
import org.example.test_03.Service.UploadFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author lands
 * @Date 2024/8/19 16:40
 * @Description 具体写接口代码的文件
 */
@Service
public class UploadFileServiceImpl implements UploadFileService {
    @Override
    public ReturnData uploadFile(MultipartFile file) throws IOException {
        String[] split = file.getOriginalFilename().split("\\.");//0.02.jpg   ["002","jpg"]
        String str = split[split.length-1];//拿到文件的后缀名

        String fileName = UUID.randomUUID().toString()+"."+str;//从新生成一个文件名

        String path = "D:/file/";//    D:/file 和 D:file 等价

        File filePath = new File(path+fileName);
        if(!filePath.exists()){//表示D:/file是不是存在这个文件夹
            filePath.mkdirs();//不存在就创建对应的文件夹
        }
        file.transferTo(filePath);


        return ReturnData.ok("http://localhost:8080/files/"+fileName);
    }
}
